﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KCMS.BusinessLogic.Interfaces;
using KCMS.DataAcsess.Interfaces;
using StructureMap;
using AutoMapper;
using KCMS.BusinessLogic.Models;
namespace KCMS.BusinessLogic.Engine
{
    public class MenuItemService : IMenuItemService
    {
        private IMenuItemManager menuItemManager = ObjectFactory.GetInstance<IMenuItemManager>();
        public Models.MenuItem getById(Guid id)
        {
            DataAcsess.Entitys.MenuItemEntity menuItemEntity = menuItemManager.getById(id);
            return Mapper.Map<DataAcsess.Entitys.MenuItemEntity, Models.MenuItem>(menuItemEntity);
        }

        public Models.MenuItem getByCodeIndex(string code, int index)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<Models.MenuItem> getAll()
        {
            return Mapper.Map<IEnumerable<DataAcsess.Entitys.MenuItemEntity>, IEnumerable<Models.MenuItem>>(menuItemManager.getAll());
        }
        private IEnumerable<MenuItem> getChildrenItems(Guid parentId)
        {
            var items = (from t in menuItemManager.getAll()
                         where t.ParentId.Equals(parentId)
                         select t).ToList();
            items.Sort((item1, item2) => item1.IndexNumber.CompareTo(item2.IndexNumber));
            return Mapper.Map<List<DataAcsess.Entitys.MenuItemEntity>, List<Models.MenuItem>>(items);
        }
        public IEnumerable<Models.MenuItem> getByMenuId(Guid menuId)
        {
           var menuItemEntities = (from t in menuItemManager.getAll()
                             where ((t.ParentId.Equals(null)||t.ParentId.Equals(Guid.Empty)) && t.MenuId.Equals(menuId))
                             select t).ToList();
           List<MenuItem> menuItems = Mapper.Map<List<DataAcsess.Entitys.MenuItemEntity>, List<Models.MenuItem>>(menuItemEntities).ToList<MenuItem>();
           menuItems.Sort((item1, item2) => item1.IndexNumber.CompareTo(item2.IndexNumber));
           menuItems.ForEach(x=>x.Items=this.getChildrenItems(x.Id));
           return menuItems;
        }


        public void update(MenuItem menuItem)
        {
            menuItemManager.update(Mapper.Map<Models.MenuItem, DataAcsess.Entitys.MenuItemEntity>(menuItem));
        }

        public void delete(Guid id)
        {
            menuItemManager.delete(id);
        }

        public void save(MenuItem menuItem)
        {
            menuItemManager.save(Mapper.Map<Models.MenuItem, DataAcsess.Entitys.MenuItemEntity>(menuItem));
        }
    }
}
